package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"server/client/casbin"
	"server/client/jwt"
	"server/config"
	"server/model/response"
)

func CasbinHandler() gin.HandlerFunc {

	return func(c *gin.Context) {
		claims, _ := c.Get("claims")
		waitUse := claims.(*jwt.JwtClaims)
		// 获取请求的URI
		obj := c.Request.URL.RequestURI()
		// 获取请求方法
		act := c.Request.Method
		// 获取用户的角色
		sub := waitUse.RoleId

		// 判断策略中是否存在

		success, _ := casbin.CasbinClient.Enforce(sub, obj, act)

		if config.GlobalConf.System.RunMode == "develop" || success {
			c.Next()
		} else {
			fmt.Printf("权限认证失败，认证信息：%s %s %s \n", sub, obj, act)
			response.FailWithDetailed(gin.H{}, "权限不足", c)
			c.Abort()
			return
		}
	}
}
